<template>
  <div class="ebook-reader">
    <div id="read"></div>
  </div>
</template>

<script>
import Epub from 'epubjs'
import {mapGetters} from 'vuex'
global.ePub = Epub
export default {
  data() {
    return {

    }
  },
  computed: {
    ...mapGetters(['fileName','menuVisible'])
  },
  methods: {
    prevPage() {
      if(this.rendition) {
        this.rendition.prev()
      }
    },
    nextPage() {
      if(this.rendition) {
        this.rendition.next()
      }
    },
    toggleTitleAndMenu() {
      this.$store.dispatch('setMenuVisible',!this.menuVisible)
    },
    toggleTitleAndMenu() {
      this.$store.dispatch('setMenuVisible',!this.menuVisible)
    },
    initEpub() {
      //http://localhost:8080/#/ebook/%E5%8F%A4%E5%85%B8%E6%96%87%E5%AD%A6|%E3%80%8A%E4%BA%BA%E7%94%9F%E3%80%8B- %E8%B7%AF%E9%81%A5
      const url = 'http://192.168.221.30:8081/epub/' + this.fileName + '.epub'
      this.book = new Epub(url)
      this.rendition = this.book.renderTo('read',{
        width: innerWidth,
        height: innerHeight,
        method: 'default'
      })
      this.rendition.display()
      this.rendition.on('touchstart', event => {
        this.touchStartX = event.changedTouches[0].clientX
        this.touchStartTime = event.timeStamp
      })
      this.rendition.on('touchend', event => {
        const offsetX = event.changedTouches[0].clientX - this.touchStartX
        const time = event.timeStamp - this.touchStartTime
        if (time < 500 && offsetX > 40) {
          this.prevPage()
        } else if (time < 500 && offsetX < -40) {
          this.nextPage()
        } else {
          this.toggleTitleAndMenu()
        }
        event.preventDefault()
        event.stopPropagation()
      })
    }
  },
  mounted() {
    const fileName = this.$route.params.fileName.split('|').join('/')
    this.$store.dispatch('setFileName', fileName).then(() => {
      this.initEpub()
    })
  }
}
</script>

<style lang="scss" scoped>
@import '../../assets/styles/global';
</style>
